package main

import (
	"encoding/hex"
	"flag"
	"fmt"
	"io/ioutil"
	"os"
	"path"
	"path/filepath"
	"xrt/constants"
	"xrt/utils"
	"xrt/utils/file/log"
)

//编译多个目录时按照目录名称输出到不同的文件, 文件间是追加关系
//根据实际情况修改的路径
var framePath = "/work/git-repository/xrt/src"

var _inner = "./xrt/components/http/static/sources"
var target = "./xrt/utils/file/asserts/data-%s.go"
var dataTemplate = `package asserts

func init() {
%s
}

`

func convertBytes2HexString(target []byte) string {
	fileHex := hex.EncodeToString(target)
	hexString := ""
	for i := 0; i < len(fileHex); i += 2 {
		hexString += fmt.Sprintf("0x%s, ", fileHex[i:i+2])
	}
	return hexString
}

func doBin(targetDir ...string) string {
	elemTemp := `    assertsData["%s"] = []byte{%s}`
	resStr := ""
	for _, dir := range targetDir {
		if dirInfo, err := os.Stat(dir); err != nil {
			log.Errorf("[%s] Stat failed: %s", dir, err.Error())
			continue
		} else {
			if dirInfo.IsDir() {
				if err := filepath.Walk(dir, func(path string, f os.FileInfo, err error) error {
					//过滤掉目录自身
					if path == dir {
						return nil
					}
					resStr += doBin(path)
					return nil
				}); err != nil {
					log.Errorf("[%s] Walk failed: %s", dir, err.Error())
				}
			} else {
				if fileContent, err := ioutil.ReadFile(dir); err != nil {
					log.Errorf("[%s] read failed: %s", dir, err.Error())
				} else {
					log.Debugf("File [%s] Do Assert Now ...", dir)
					resStr += fmt.Sprintf(elemTemp, dir, convertBytes2HexString(fileContent))
					resStr += constants.LineSep
				}
			}
		}
	}
	return resStr
}

var staticDir = flag.String("d", path.Join(framePath, _inner), "Use -d [dir]")
var targetTag = flag.String("t", "", "Use -t [tag]")

func main() {
	flag.Parse()
	if *targetTag == "" {
		targetTag = &utils.RSplitN(*staticDir, "/", 2)[1]
	}
	dataFile := path.Join(framePath, fmt.Sprintf(target, *targetTag))
	os.Create(dataFile)
	if wf, err := os.OpenFile(dataFile, os.O_WRONLY, 0644); err != nil {
		log.Errorf("Write BinFile Error: [%s].", err.Error())
	} else {
		defer wf.Close()
		fileContent := doBin(*staticDir)
		wf.WriteString(fmt.Sprintf(dataTemplate, fileContent))
	}
}
